﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using System.Linq;
using Pakxel.Data;
using Telerik.WinControls.UI;
using System.Data.Common;

namespace Pakxel.SmartLogistic
{
    public partial class ValeDieselWorkBench : BaseWorkBench
    {
        public ValeDieselWorkBench()
        {
            InitializeComponent();
        }

        void SetupValesGrid()
        {
           this.Width = 615;
           this.Height = 588;

           /// TODO ADD : if user is in ROLE (Admin, Supervisor) change to true
           ValesGrid.AllowEditRow = false;

           GridViewTextBoxColumn colT005NoViaje = new GridViewTextBoxColumn("T005NoViaje", "T005NoViaje");
           colT005NoViaje.HeaderText = "Num Viaje";
           colT005NoViaje.IsVisible = false;
           colT005NoViaje.Width = 100;

           GridViewTextBoxColumn colT020Folio = new GridViewTextBoxColumn("T020Folio", "T020Folio");
           colT020Folio.HeaderText = "Folio";
           colT020Folio.Width = 100;

           GridViewDateTimeColumn colT020FechaVale = new GridViewDateTimeColumn("T020FechaVale", "T020FechaVale");
           colT020FechaVale.HeaderText = "Fecha Vale";
           colT020FechaVale.FormatInfo = new System.Globalization.CultureInfo("es-MX");
           colT020FechaVale.FormatString = "{0:dd/MM/yyyy hh:mm tt}";
           colT020FechaVale.Width = 150; 

           GridViewTextBoxColumn colT020Litros = new GridViewTextBoxColumn("T020Litros", "T020Litros");
           colT020Litros.HeaderText = "Litros";
           colT020Litros.Width = 100;

           GridViewTextBoxColumn colT020Monto = new GridViewTextBoxColumn("T020Monto", "T020Monto");
           colT020Monto.HeaderText = "Monto";
           colT020Monto.FormatInfo = new System.Globalization.CultureInfo("es-MX");
           colT020Monto.FormatString = "{0:C}";
           colT020Monto.Width = 200;

           GridViewTextBoxColumn colT020Cancelado = new GridViewTextBoxColumn("T020Cancelado", "T020Cancelado");
           colT020Cancelado.HeaderText = "Cancelado";
           colT020Cancelado.GetDefaultEditor().Value = "N";
           colT020Cancelado.IsVisible = false;

           ValesGrid.Columns.Add(colT005NoViaje);
           ValesGrid.Columns.Add(colT020Folio);
           ValesGrid.Columns.Add(colT020FechaVale);
           ValesGrid.Columns.Add(colT020Litros);
           ValesGrid.Columns.Add(colT020Monto);
           ValesGrid.Columns.Add(colT020Cancelado); 
        }

        private void ValeDiese_Load(object sender, EventArgs e)
        {
            SetupValesGrid(); 
            DataContext = new Data.MEDataDataContext(WorkBench.ConnectionString);
            tsbNvo.Click += new EventHandler(tsbNvo_Click);
            tsbSave.Click += new EventHandler(tsbSave_Click);
            tsbEdit.Click += new EventHandler(tsbEdit_Click);
            WorkBenchFilter.KeyDown += new KeyEventHandler(WorkBenchFilter_KeyDown);
        }

        void WorkBenchFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (Viaje != null)
                {
                  ValesGrid.DataSource = from D in DataContext.T020s where D.T005NoViaje.Equals(Viaje.T005NoViaje) && D.T020Cancelado.ToString().Equals("N")  select D;
                }
                else
                {
                    ClearControls(this.Controls);
                    ValesGrid.DataSource = null;
                }
            }
        }

        void tsbEdit_Click(object sender, EventArgs e)
        {
            /// TODO : Validar Rol del usuario
            /// Activar al eliminacion de renglones en el grid
            /// Buscar el registro y eliminarlo de la bd
        }

        void tsbSave_Click(object sender, EventArgs e)
        {
           if (Viaje != null)
           {
              Int32 Liquidado = (from L in DataContext.T005s where L.T005NoViaje.Equals(Viaje.T005NoViaje) && !L.T016IdLiquidacion.Equals(null) select L.T016IdLiquidacion).Count();
              if (Liquidado == 0)
              {
                 if (DataContext.Connection.State == ConnectionState.Closed)
                 {
                    DataContext.Connection.Open();
                 }
                 using (DbTransaction transaction = DataContext.Connection.BeginTransaction(IsolationLevel.Serializable))
                 {
                    DataContext.Transaction = transaction;
                    try
                    {
                       // Buscar Vale de disel si ya existe no actualizar ni grabar nada.
                       foreach (Telerik.WinControls.UI.GridViewRowInfo Row in ValesGrid.Rows)
                       {
                          if (Row != null)
                          {
                             if(Convert.ToInt32(Row.Cells["T020Litros"].Value)>0 
                                && Convert.ToInt32(Row.Cells["T020Monto"].Value)>0)
                             {
                                if (Convert.ToInt32(Row.Cells["T020Folio"].Value)<= 0)
                                {
                                   if (Convert.ToInt32(Row.Cells["T020Folio"].Value) <= 0)
                                   {
                                      int NoAnt = 0;
                                      T014 Parametros = (from P in DataContext.T014s where P.T014IdParametro.Equals("FOLVALE") select P).SingleOrDefault();
                                      if (Parametros != null)
                                      {
                                         NoAnt = Convert.ToInt32(Parametros.T014Val1);
                                         NoAnt++;
                                         Parametros.T014Val1 = Convert.ToString(NoAnt);
                                         //ValesGrid.Columns["T020Folio"].ReadOnly = false;
                                         Row.Cells["T020Folio"].Value = NoAnt;
                                         //ValesGrid.Columns["T020Folio"].ReadOnly = true;
                                         Row.Cells["T005NoViaje"].Value = Viaje.T005NoViaje.ToString();
                                         Row.Cells["T020Cancelado"].Value = Convert.ToChar('N');
                                      }
                                   }
                                }
                             }
                          }
                       }
                       DataContext.SubmitChanges();
                       transaction.Commit(); 
                    }
                    catch (Exception ex)
                    {
                       transaction.Rollback();
                       MainApp.WriteExceptionToLog(ex);
                    }
                    finally
                    {
                       ValesGrid.DataSource = from A in DataContext.T020s where A.T005NoViaje.Equals(Convert.ToInt32(WorkBenchFilter.Text)) select A;
                       DataContext.Connection.Close();
                    }
                 }
              }
           }
           else
           {
              ClearControls(this.Controls);
              ValesGrid.DataSource = null;
              Viaje = null;
           }
        }

        void tsbNvo_Click(object sender, EventArgs e)
        {
            ClearControls(this.Controls);
            ValesGrid.DataSource = null;
            Viaje = null;
        }

        private void ValesGrid_CellBeginEdit(object sender, GridViewCellCancelEventArgs e)
        {
           if (e.Column.Name.Equals("T020Folio") )
           {
              e.Cancel = true;
           }
        }
    }
}
